package com.xxc.response.handler

import com.xxc.common.util.RequestContextHolderUtil
import com.xxc.common.anotation.POKO
import com.xxc.response.constant.RESPONSE_RESULT
import com.xxc.response.result.PlatformResult
import org.springframework.core.MethodParameter
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice
import kotlin.reflect.KClass

@POKO
@ControllerAdvice
class ResponseResultHandler:ResponseBodyAdvice<Any> {
    override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean {
        val type:KClass<*>? = RequestContextHolderUtil.getRequest().getAttribute(RESPONSE_RESULT) as KClass<*>?
        return type != null
    }

    override fun beforeBodyWrite(body: Any?, returnType: MethodParameter, selectedContentType: MediaType, selectedConverterType: Class<out HttpMessageConverter<*>>, request: ServerHttpRequest, response: ServerHttpResponse): Any? {
        val type:KClass<*> = RequestContextHolderUtil.getRequest().getAttribute(RESPONSE_RESULT) as KClass<*>
        if(body is PlatformResult<*>)
            return body
            //如果是通用响应类则进行创建返回
        return if(type == PlatformResult::class) {
            PlatformResult.success(body)
        }else{
            body
        }
    }
}